#!/bin/bash
# author tyb


# 执行结果判断函数
function isgreen() {
    if [ $? -eq 0 ]; then
        echo -e "\e[32m$1==========>succeed\e[0m"
    else
        echo -e "\e[31m$1==========>failed\e[0m"
        # exit 1
    fi
}

# 内核版本降级到5.19
# 查看系统中是否包含5.19内核
function downgrades(){
    echo "降级内核至5.19......"
    if dpkg --get-selections | grep linux-image-5.19 >/dev/null 2>&1
    then
        cp /etc/default/grub /etc/default/grub.bak
        isgreen "backup grub config file"
        core_version="$(grep -i menuentry /boot/grub/grub.cfg | grep -i "Linux 5.19" | head -1 | awk -F"'" '{print $2}' | awk -F", " '{print $2}')"
        cat << EOF > /etc/default/grub
GRUB_DEFAULT="Advanced options for Ubuntu>Ubuntu, $core_version"
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=0
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT=""
GRUB_CMDLINE_LINUX="intel_iommu=on kvm.ignore_msrs=1 cpufreq.default_governor=performance intel_pstate=disable"
GRUB_DISABLE_OS_PROBER=false
EOF
        isgreen "modifity grub config file"
        update-grub
        isgreen "update grub"

        echo -e "\e[31mplease reboot !!!\e[0m"
        echo ""

    else
        echo -e "\e[31mThere is no kernel version 5.19 in the system\e[0m"
        exit 1
    fi
}




# 检测系统内核版本是否为5.19
if ! [[ "$(uname -r)" == *"5.19"* ]];
then
    echo -e "\e[31mcore version is $(uname -r)\e[0m"
    echo -n "Are you sure you want to downgrade to 5.19? [y|yes|n|no]:"
    read -r is_ok
    if [ "$is_ok" == "y" ] || [ "$is_ok" == "yes" ]
    then
       downgrades
    else
        exit
    fi 
else
    echo -e "\e[32mcore version is $(uname -r)\e[0m"
fi 